import { defineStore } from 'pinia'
import { ref, watch } from 'vue'

export type Theme = 'light' | 'dark' | 'auto'

export const useThemeStore = defineStore('theme', () => {
  const theme = ref<Theme>(localStorage.getItem('theme') as Theme || 'auto')

  // 初始化主题
  const initTheme = () => {
    applyTheme(theme.value)
  }

  // 应用主题
  const applyTheme = (newTheme: Theme) => {
    const htmlElement = document.documentElement
    htmlElement.classList.remove('light', 'dark')

    if (newTheme === 'auto') {
      const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches
      htmlElement.classList.add(isDark ? 'dark' : 'light')
    } else {
      htmlElement.classList.add(newTheme)
    }
  }

  // 设置主题
  const setTheme = (newTheme: Theme) => {
    theme.value = newTheme
    localStorage.setItem('theme', newTheme)
    applyTheme(newTheme)
  }

  // 监听系统主题变化
  if (theme.value === 'auto') {
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    mediaQuery.addEventListener('change', () => {
      if (theme.value === 'auto') {
        applyTheme('auto')
      }
    })
  }

  // 监听 theme 变化
  watch(theme, (newTheme) => {
    applyTheme(newTheme)
  })

  return {
    theme,
    initTheme,
    setTheme
  }
})
